package com.chy.blog_web.modular.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chy.blog_web.core.util.GetUserIpAddressUtil;
import com.chy.blog_web.core.util.PageAndParamUtil;
import com.chy.blog_web.modular.system.entity.SysMenu;
import com.chy.blog_web.modular.system.service.ISysMenuService;
import com.chy.blog_web.modular.web.entity.*;
import com.chy.blog_web.modular.web.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * 描述：我的相册 controller
 * 作者：chenhuiyan
 * 时间：2020/03/06 22:07
 */
@Controller
@RequestMapping(value = "/myAlbum")
public class MyAlbumController {

    /**
     * 前缀
     */
    private static String PREFIX = "web/myAlbum/";

    /**
     * 导航service
     */
    @Autowired
    private ISysMenuService sysMenuService;

    /**
     * 内容service
     */
    @Autowired
    private IBoContentService boContentService;

    /**
     * 相册service
     */
    @Autowired
    private IBoPhotoAlbumService boPhotoAlbumService;

    /**
     * 照片service
     */
    @Autowired
    private IBoPhotoService boPhotoService;

    /**
     * 评论service
     */
    @Autowired
    private IBoCommentService boCommentService;

    /**
     * 文章service
     */
    @Autowired
    private IBoArticleService boArticleService;


    /**
     * 跳转我的相册页面
     * @return
     */
    @RequestMapping(value = "")
    public String index(){
        return PREFIX + "myAlbum";
    }

    /**
     * 查询导航、LOGO标题、页脚
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getMyAlbumData")
    public Map<String, Object> getMyAlbumData(){
        Map<String, Object> res = new HashMap<>();
        try{
            //查询前台显示导航，并且按创建时间升序排序
            List<SysMenu> sysMenuList = sysMenuService.getBaseMapper()
                    .selectList(new QueryWrapper<SysMenu>()
                            .eq("type", 1)
                            .eq("is_show", 0)
                            .eq("del_flag", 0)
                            .orderByAsc("sort"));

            //查询LOGO标题，编号为：521f1cd04f9d4345af2e62213178d6ac
            BoContent logoTitle = boContentService.getById("521f1cd04f9d4345af2e62213178d6ac");

            //查询页脚，编号为：5d8530c950d243e18e57b74190aa2d94
            BoContent indexFooter = boContentService.getById("5d8530c950d243e18e57b74190aa2d94");

            res.put("sysMenuList", sysMenuList);
            res.put("logoTitle", logoTitle);
            res.put("indexFooter", indexFooter);
            res.put("state", "200");
            res.put("message", "初始化成功");
        }catch (Exception e){
            e.printStackTrace();
            res.put("state", "500");
            res.put("message", "服务器异常，请重新刷新页面！");
        }

        return res;
    }

    /**
     * 查询相册列表
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getPhotoAlbumList")
    public Map<String, Object> getPhotoAlbumList(){
        Map<String, Object> res = new HashMap<>();
        Map<String, Object> params = PageAndParamUtil.getParams();
        try {
            List<Map<String, Object>> photoAlbumList = boPhotoAlbumService.list(params);
            Integer count = boPhotoAlbumService.getBaseMapper().selectCount(new QueryWrapper<BoPhotoAlbum>()
                    .eq("is_show", 0)
                    .eq("del_flag", 0)); //获取总数
            res.put("state", "200");
            res.put("message", "查询相册列表成功");
            res.put("photoAlbumList", photoAlbumList);
            res.put("count", count);
        }catch (Exception e){
            e.printStackTrace();
            res.put("state", "500");
            res.put("message", "服务器异常，请重新刷新页面！");
        }
        return res;
    }

    /**
     * 跳转照片/视频页面
     * @return
     */
    @RequestMapping(value = "/photo")
    public String photo(@RequestParam(name = "albumId") String albumId, Model model){
        BoPhotoAlbum boPhotoAlbum = boPhotoAlbumService.getById(albumId);
        model.addAttribute("albumId", albumId);
        //判断是视频还是照片
        if(boPhotoAlbum.getType() == 0){
            return PREFIX + "photo";
        }else{
            return PREFIX + "photoVideo";
        }
    }

    /**
     * 根据相册编号查询照片列表：查询前先进行相册密码检验
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getPhotoList")
    public Map<String, Object> getPhotoList(@RequestParam(name = "albumId") String albumId){
        Map<String, Object> res = new HashMap<>();
        try {
            //判断是否加锁和进行密码校验
            boolean flag = validPassword(albumId);
            if(!flag){
                res.put("state", "500");
                res.put("message", "相册已加锁");
                return res;
            }

            List<BoPhoto> photoList = new ArrayList<>();

            Map<String, Object> params = PageAndParamUtil.getParams();

            photoList = boPhotoService.list(params);

            //总数
            Integer count = boPhotoService.getBaseMapper().selectCount(new QueryWrapper<BoPhoto>()
                    .eq("photo_album_id", albumId)
                    .eq("del_flag", 0));

            //查询相册信息
            Map<String, Object> photoAlbum = boPhotoAlbumService.getInfoById(albumId);

            res.put("state", "200");
            res.put("message", "查询照片列表成功");
            res.put("photoList", photoList);
            res.put("count", count);
            res.put("photoAlbum", photoAlbum);
        }catch (Exception e){
            e.printStackTrace();
            res.put("state", "500");
            res.put("message", "服务器异常，请重新刷新页面！");
        }
        return res;
    }

    /**
     * 验证加锁相册密码，验证通过则保存Session
     * @param albumPassword
     * @param albumId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/validPhotoPassword")
    public Map<String, Object> validPhotoPassword(@RequestParam(name = "albumPassword") String albumPassword, @RequestParam(name = "albumId") String albumId){
        Map<String, Object> res = new HashMap<>();
        try {
            //密码验证
            BoPhotoAlbum boPhotoAlbum = boPhotoAlbumService.getById(albumId);
            if(albumPassword.equals(boPhotoAlbum.getPassword())){
                HttpServletRequest request = PageAndParamUtil.getRequest();
                HttpSession session = request.getSession();
                session.setAttribute("albumPassword", albumPassword); //密码验证通过，保存session
                res.put("state", "200");
                res.put("message", "密码验证通过");
            }else{
                res.put("state", "500");
                res.put("message", "密码验证不通过");
            }
        }catch (Exception e){
            e.printStackTrace();
            res.put("state", "500");
            res.put("message", "服务器异常，请重新刷新页面！");
        }
        return res;
    }

    /**
     * 判断是否加锁和进行密码校验
     * @param albumId
     * @return
     */
    public boolean validPassword(String albumId){
        //内容保存密码的编号：a0edf31ba84a4517bfb36dc7bbe37732
        BoPhotoAlbum boPhotoAlbum = boPhotoAlbumService.getById(albumId);
        HttpServletRequest request = PageAndParamUtil.getRequest();
        HttpSession session = request.getSession();
        String albumPassword = session.getAttribute("albumPassword") + "";

        //判断是否加锁
        if(boPhotoAlbum.getIsLock() == 0){
            return true;
        }

        if(albumPassword == null || albumPassword == ""){
            return false;
        }else if(albumPassword.equals(boPhotoAlbum.getPassword())){
            return true;
        }
        return false;
    }

    /**
     * 相册点赞
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updatePraiseNum")
    public Map<String, Object> updatePraiseNum(@RequestParam(name = "id") String id, HttpServletRequest request){
        Map<String, Object> res = new HashMap<>();

        //获取ip地址
        String ipAddress = GetUserIpAddressUtil.getIpAddress(request);
        try {

            //判断是否加锁和进行密码校验
            boolean v_flag = validPassword(id);
            if(!v_flag){
                res.put("state", "500");
                res.put("message", "相册已加锁");
                return res;
            }

            boolean flag = boPhotoAlbumService.updatePraiseNum(id, ipAddress);
            if(flag){
                res.put("state", "200");
                res.put("message", "已赞 >_<");
            }else{
                res.put("state", "500");
                res.put("message", "您今天已点过赞 >_<");
            }
        }catch (Exception e){
            res.put("state", "500");
            res.put("message", "服务器异常点赞失败！");
            e.printStackTrace();
        }
        return res;
    }

    /**
     * 更新阅读数量
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateReadNum")
    public Map<String, Object> updateReadNum(@RequestParam(name = "id") String id){
        Map<String, Object> res = new HashMap<>();
        try{
            //判断是否加锁和进行密码校验
            boolean v_flag = validPassword(id);
            if(!v_flag){
                res.put("state", "500");
                res.put("message", "相册已加锁");
                return res;
            }

            BoPhotoAlbum boPhotoAlbum = boPhotoAlbumService.getById(id);
            boPhotoAlbum.setReadNum(boPhotoAlbum.getReadNum() + 1);
            boPhotoAlbumService.updateById(boPhotoAlbum);
            res.put("state", "200");
            res.put("message", "阅读数量更新成功");
        }catch (Exception e){
            e.printStackTrace();
            res.put("state", "500");
            res.put("message", "服务器异常");
        }
        return res;
    }

    /**
     * 根据业务编号和分类查询评论列表
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getCommList")
    public Map<String, Object> getCommList(@RequestParam(name = "id") String id){
        Map<String, Object> res = new HashMap<>();
        try {

            //判断是否加锁和进行密码校验
            boolean v_flag = validPassword(id);
            if(!v_flag){
                res.put("state", "500");
                res.put("message", "相册已加锁");
                return res;
            }

            //查询留言
            Map<String, Object> params = PageAndParamUtil.getParams();
            params.put("classify", 1);
            params.put("serviceId", id);
            List<Map<String, Object>> commList = boCommentService.getList(params);
            //总数
            Integer count = boCommentService.getBaseMapper()
                    .selectCount(new QueryWrapper<BoComment>()
                            .eq("del_flag", 0)
                            .eq("type", 0)
                            .eq("service_id", id)
                            .eq("classify", 1));

            //查询回复总数
            Integer referCount = boCommentService.getBaseMapper()
                    .selectCount(new QueryWrapper<BoComment>()
                            .eq("del_flag", 0)
                            .eq("type", 1)
                            .eq("service_id", id)
                            .eq("classify", 1));

            res.put("state", "200");
            res.put("message", "查询评论成功");
            res.put("commList", commList);
            res.put("count", count);
            res.put("referCount", referCount);
        }catch (Exception e){
            res.put("state", "500");
            res.put("message", "服务器异常，请重新刷新页面！");
            e.printStackTrace();
        }
        return res;
    }

    /**
     * 添加评论
     * @param boComment
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/addComment")
    public Map<String, Object> addComment(BoComment boComment){
        Map<String, Object> res = new HashMap<>();
        try{

            //判断是否加锁和进行密码校验
            boolean v_flag = validPassword(boComment.getServiceId());
            if(!v_flag){
                res.put("state", "500");
                res.put("message", "相册已加锁");
                return res;
            }

            //不输入用户名则默认
            Random random = new Random();
            if("".equals(boComment.getUserName()) || boComment.getUserName() == null){
                boComment.setUserName("匿名用户_" + random.nextInt(99999));
            }

            //回复时，不输入用户名则默认
            if(boComment.getType() == 1 && ("".equals(boComment.getByUserName()) || boComment.getByUserName() == null)){
                boComment.setByUserName("匿名用户_" + random.nextInt(99999));
            }

            //评论内容双引号处理
            boComment.setContent(boComment.getContent().replaceAll("\"",  "'"));

            boComment.preInsert();
            boCommentService.save(boComment);

            res.put("state", "200");
            res.put("message", "已发布>_<");
        }catch (Exception e){
            res.put("state", "500");
            res.put("message", "服务器异常,评论失败>_<");
            e.printStackTrace();
        }
        return res;
    }

    /**
     * 评论点赞
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/commPraise")
    public Map<String, Object> commPraise(@RequestParam(name = "id") String id, HttpServletRequest request){
        Map<String, Object> res = new HashMap<>();

        //获取ip地址
        String ipAddress = GetUserIpAddressUtil.getIpAddress(request);
        try {
            boolean flag = boArticleService.commPraise(id, ipAddress);
            if(flag){
                res.put("state", "200");
                res.put("message", "已赞 >_<");
            }else{
                res.put("state", "500");
                res.put("message", "您今天已点过赞 >_<");
            }
        }catch (Exception e){
            res.put("state", "500");
            res.put("message", "服务器异常点赞失败！");
            e.printStackTrace();
        }
        return res;
    }

}
